//
//  MyGradesViewController.m
//  JiuLe
//
//  Created by SunChao on 16/10/10.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "MyGradesViewController.h"
#import "YJSegmentedControl.h"
#import "GradesTableViewCell.h"
#import "BaseDataRequest.h"

typedef NS_ENUM(NSInteger, UITableViewType) {
    UITableViewTypeDefault, //积分历史
    UITableViewTypeRule,    //积分规则
};


@interface MyGradesViewController ()<UITableViewDelegate,UITableViewDataSource,YJSegmentedControlDelegate,UIWebViewDelegate>
@property (weak, nonatomic) YJSegmentedControl *segment;
@property (strong, nonatomic) NSMutableArray *arrDatasource;
@property (strong, nonatomic) UITableView *tableView;
@property (assign, nonatomic) UITableViewType  tableViewType;
@property (assign, nonatomic) NSInteger page;
@property (strong, nonatomic) NSDictionary *dicModel;

@end

@implementation MyGradesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的积分";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    [self createUISegmentedControl];
    [self createTableView];
    [self separatorForTableView:self.tableView];
    self.page = 1;
    [self getGredes];
}

#pragma mark - 数据请求
- (void)getGredes{
    [SVProgressHUD showWithStatus:@"获取积分.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"token"] forKey:@"token"];
    [dict setObject:[NSString stringWithFormat:@"%d",(int)self.page] forKey:@"page"];
    [[BaseDataRequest alloc] getGrades:dict WithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [self.tableView.footer endRefreshing];
        if ([status isEqualToString:@"0"]) {
            self.dicModel = [responseObject objectForKey:@"result"];
            NSMutableArray *arrResult = [NSMutableArray arrayWithArray:[self.dicModel objectForKey:@"list"]];
            if (arrResult.count == 0 || arrResult.count < 8) {
                [self.tableView.footer noticeNoMoreData];
            }
            [self.arrDatasource addObjectsFromArray:arrResult];
            [self.tableView reloadData];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.tableViewType == UITableViewTypeDefault) {
        return self.arrDatasource.count;
    }else{
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableViewType == UITableViewTypeDefault) {
        static NSString *CellIdentifier = @"GradesTableViewCell";
        GradesTableViewCell *cell = (GradesTableViewCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil){
            cell = (GradesTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:@"GradesTableViewCell" owner:self options:nil] lastObject];
        }
        NSMutableDictionary *model = _arrDatasource[indexPath.row];
        cell.labTitle.text = [model objectForKey:@"name"];
        cell.labTime.text = [model objectForKey:@"time"];
        if ([[model objectForKey:@"iotype"] isEqualToString:@"1"]) {
            cell.labGrades.text = [NSString stringWithFormat:@"-%@",[model objectForKey:@"points"]];
            cell.labGrades.textColor = RGB(132, 167, 84);
        }else{
            cell.labGrades.text = [NSString stringWithFormat:@"+%@",[model objectForKey:@"points"]];
            cell.labGrades.textColor = RGB(253, 102, 0);
        }
        return cell;
    }else{
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"webCell"];
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 44 - 64)];
        [cell.contentView addSubview:webView];
        webView.delegate = self;
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                        initWithURL:[NSURL URLWithString:@"http://www.jiuletech.com:8088/jifen.htm"]
                                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                                        timeoutInterval:15.f];
        [webView loadRequest:request];
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *heatView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
    heatView.backgroundColor = [UIColor redColor];
    UIImageView *imageBG = [[UIImageView alloc] initWithFrame:heatView.frame];
    imageBG.image = [UIImage imageNamed:@"icon_grades"];
    UILabel *labTitle = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, 200, 20)];
    labTitle.textColor = [UIColor whiteColor];
    labTitle.text = @"我的积分";
    labTitle.font = [UIFont systemFontOfSize:15];
    UILabel *labGrades = [[UILabel alloc] initWithFrame:CGRectMake(15, 40, 200, 45)];
    labGrades.textColor = [UIColor whiteColor];
    labGrades.text = [self stringToString:[NSString stringWithFormat: @"%@",[self.dicModel objectForKey:@"score"]]];
    labGrades.font = [UIFont systemFontOfSize:50];
    [heatView addSubview:imageBG];
    [heatView addSubview:labTitle];
    [heatView addSubview:labGrades];
    return heatView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableViewType == UITableViewTypeDefault) {
        return 59;
    }else{
        return SCREEN_HEIGHT - 44 - 64;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.tableViewType == UITableViewTypeDefault) {
        return 100;
    }else{
        return 0;
    }
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView{
    NSLog(@"webViewDidStartLoad");
}

- (void)webViewDidFinishLoad:(UIWebView *)web{
    UIActivityIndicatorView *testActivityIndicator = [self.view viewWithTag:12];
    [testActivityIndicator removeFromSuperview];
}

- (void)webView:(UIWebView*)webView  DidFailLoadWithError:(NSError*)error{
    NSLog(@"DidFailLoadWithError");
}

#pragma mark - 遵守代理 实现代理方法
- (void)segumentSelectionChange:(NSInteger)selection{
    [self.tableView scrollsToTop];
    if (selection == 0) {
        self.tableViewType = UITableViewTypeDefault;
        UIActivityIndicatorView *testActivityIndicator = [self.view viewWithTag:12];
        [testActivityIndicator removeFromSuperview];
    }else if (selection == 1){
        [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
        self.tableViewType = UITableViewTypeRule;
        UIActivityIndicatorView *testActivityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        testActivityIndicator.center = CGPointMake(SCREEN_WIDTH/2, SCREEN_HEIGHT/2-64);
        [testActivityIndicator startAnimating];
        testActivityIndicator.tag = 12;
        [self.view addSubview:testActivityIndicator];
        [self.view bringSubviewToFront:testActivityIndicator];
    }
    [self.tableView reloadData];
}

#pragma mark set/get
- (NSMutableArray *)arrDatasource{
    if (_arrDatasource == nil) {
        _arrDatasource = [NSMutableArray array];
    }
    return _arrDatasource;
}

#pragma mark - 私有方法
- (void)createUISegmentedControl{
    NSArray * btnDataSource = @[@"积分历史", @"积分规则"];
    YJSegmentedControl * segment = [YJSegmentedControl segmentedControlFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44) titleDataSource:btnDataSource backgroundColor:[UIColor colorWithRed:253.0f/255 green:239.0f/255 blue:230.0f/255 alpha:1.0f] titleColor:[UIColor grayColor] titleFont:[UIFont fontWithName:@".Helvetica Neue Interface" size:16.0f] selectColor:[UIColor orangeColor] buttonDownColor:[UIColor redColor] Delegate:self];
    [self.view addSubview:segment];
}

- (void)createTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height-44-64) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        weakSelf.page ++;
        [weakSelf getGredes];
    }];
}

- (NSString *)stringToString:(NSString *)string{
    if([string isEqualToString:@"(null)"] || string == nil || string == NULL){
        return @"0";
    }
    return string;
}

@end
